package com.wcpdoc.survey.home.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wcpdoc.survey.core.controller.BaseController;
import com.wcpdoc.survey.core.entity.PageResult;
import com.wcpdoc.survey.core.util.NetworkUtil;
import com.wcpdoc.survey.core.util.ValidateUtil;
import com.wcpdoc.survey.home.service.HomeSurveyService;
import com.wcpdoc.survey.survey.entity.PaperQuestionEx;
import com.wcpdoc.survey.survey.entity.Survey;
import com.wcpdoc.survey.sys.cache.DictCache;
import com.wcpdoc.survey.sys.entity.Dict;

/**
 * 首页调查控制层
 * 
 * v1.0 zhanghc 2017年10月16日下午6:23:38
 */
@Controller
@RequestMapping("/home/survey")
public class HomeSurveyController extends BaseController{
	private static final Logger log = LoggerFactory.getLogger(HomeSurveyController.class);
	
	@Resource
	private HomeSurveyService homeExamService;
	
	/**
	 * 到达问卷页面
	 * 
	 * v1.0 zhanghc 2017年10月16日下午6:23:38
	 * @param model
	 * @param examUserId
	 * @return String
	 */
	@RequestMapping("/pubToPaper")
	public String toPaper(Model model, Integer surveyId) {
		try {
			Survey survey = homeExamService.getSurvey(surveyId);
			if(survey.getState() == 0){
				throw new RuntimeException("【"+survey.getName()+"】已"+DictCache.getDictValue("SURVEY_STATE", "0")+"！" );
			}
			if(survey.getState() == 2){
				throw new RuntimeException("【"+survey.getName()+"】"+DictCache.getDictValue("SURVEY_STATE", "1")+"！" );
			}
			if(survey.getEndTime().getTime() < new Date().getTime()){
				throw new RuntimeException("调查【"+survey.getName()+"】已结束！");
			}
			
			List<PaperQuestionEx> paperQuestionExList = homeExamService.getPaperList(survey.getPaperId());
			model.addAttribute("survey", survey);
			model.addAttribute("paperQuestionExList", paperQuestionExList);
			List<Dict> list = DictCache.getIndexDictlistMap().get("QUESTION_OPTIONS");
			Map<Integer, String> questionDictMap = new HashMap<>();
			for(Dict dict : list){
				questionDictMap.put(Integer.parseInt(dict.getDictKey()), dict.getDictValue());
			}
			model.addAttribute("dictMap", questionDictMap);
			
			return "/WEB-INF/jsp/home/survey/homePaperList.jsp";
		} catch (Exception e) {
			log.error("到达问卷页面错误：", e);
			model.addAttribute("message", e.getMessage());
			return "/WEB-INF/jsp/home/survey/homePaperEnd.jsp";
		}
	}
	
	/**
	 * 更新答案
	 * 
	 * v1.0 zhanghc 2017年10月25日下午3:51:22
	 * @param questionId
	 * @param answer
	 * @return PageResult
	 */
	@RequestMapping("/pubUpdateAnswer")
	@ResponseBody
	public PageResult updateAnswer(Integer questionId, String answer) {
		try {
			Context context = getContext(request.getSession());
			if(!ValidateUtil.isValid(answer)){
				context.CACHE.remove(questionId);
			}else {
				context.CACHE.put(questionId, answer);
			}
			
			return new PageResult(true, "更新成功");
		} catch (Exception e) {
			log.error("更新答案错误：", e);
			return new PageResult(false, "更新失败：" + e.getMessage());
		}
	}
	
	/**
	 * 完成问卷
	 * 
	 * v1.0 zhanghc 2017年10月16日下午6:23:38
	 * @param examUserId
	 * @return PageResult
	 */
	@RequestMapping("/pubDoPaper")
	@ResponseBody
	public PageResult doPaper(Integer surveyId) {
		try {
			homeExamService.doPaper(surveyId, NetworkUtil.getRemoteIp(request), getContext(request.getSession()).CACHE);
			return new PageResult(true, "完成问卷成功");
		} catch (Exception e) {
			log.error("完成问卷错误：", e);
			return new PageResult(false, "完成问卷失败：" + e.getMessage());
		}
	}
	
	/**
	 * 到达问卷结束页面
	 * 
	 * v1.0 zhanghc 2017年10月26日下午3:14:20
	 * @param model
	 * @return String
	 */
	@RequestMapping("/pubToEnd")
	public String toHome(Model model) {
		try {
			model.addAttribute("message", "感谢参与！");
			return "/WEB-INF/jsp/home/survey/homePaperEnd.jsp";
		} catch (Exception e) {
			log.error("到达问卷结束页面错误：", e);
			return "/WEB-INF/jsp/home/survey/homePaperEnd.jsp";
		}
	}
	
	private Context getContext(HttpSession session) {
		Context context = (Context) session.getAttribute("CONTEXT");
		if (context != null) {
			return context;
		}
		
		context = new Context();
		session.setAttribute("CONTEXT", context);
		return context;
	}
	
	private class Context{
		private Map<Integer, String> CACHE = new HashMap<>();
	}
}
